﻿using System;
using System.Activities.Statements;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HomeWork11_Order
{
    public class OrderService
    {
        //添加订单
        public void AddOrder()
        {
            Console.WriteLine("添加订单");
            using (var context = new OrderContext())
            {
                Order newOrder = new Order();

                newOrder.OrderItems = new List<OrderItem>();
                
                //录入客户信息
                newOrder.Client = ReadClientName();
                //产生订单号
                newOrder.OrderId = ProduceOrderID();
                //展示所有订单
                ShowOrders();
                //添加订单明细
                AddOrderItems(newOrder);

                //添加订单
                context.Orders.Add(newOrder);
                newOrder.ClientName = newOrder.Client.ClientName;
                context.SaveChanges();
                Console.WriteLine($"添加成功，订单号是: {newOrder.OrderId}, 客户名是：{newOrder.Client}");               
            }
        }

        //删除订单
        public void DeleteOrder()
        {
            int orderID = -1;

            Console.WriteLine("删除订单：");
            Console.WriteLine("输入要删除的订单号");
            try
            {
                orderID = Convert.ToInt32(Console.ReadLine());
                if (orderID <= 0) { Console.WriteLine("请输入正确的订单号！"); return; }
                DeleteOrderByOrderID(orderID);
            }
            catch
            {
                Console.WriteLine("请输入正确的订单号！");
            }
           
        }

        //查找订单
        public void QueryOrder()
        {
            Console.WriteLine("修改订单：");
            Console.WriteLine("请选择查询方式： ");
            Console.WriteLine("C：按客户名查询； O：按订单号查询；P：按商品名查询");
            switch (Console.ReadLine())
            {
                case "C":
                    Console.WriteLine("请输入客户名：");
                    QueryByClientName(Console.ReadLine());
                    break;
                case "O":
                    Console.WriteLine("请输入订单号：");
                    try
                    {
                        int orderID = Convert.ToInt32(Console.ReadLine());
                        if (orderID <= 0) { Console.WriteLine("输入正确的订单号！"); return; }
                        QueryByOrderID(orderID);
                        break;
                    }
                    catch
                    {
                        Console.WriteLine("输入正确的订单号！");
                        break;
                    }
                case "P":
                    Console.WriteLine("请输入商品名称：");
                    QueryByProductName(Console.ReadLine());
                    break;
                default:
                    Console.WriteLine("请输入正确的操作！");
                    break;
            }
        }

        //修改订单
        public void ModifyOrder()
        {
            int oldOrderID = -1;
            //Order ModifyOrder = new Order();
           //ModifyOrder.OrderItems = new List<OrderItem>();

            Console.WriteLine("修改订单：");
            Console.WriteLine("请输入要修改的订单号：");
 
            try
            {
                oldOrderID = Convert.ToInt32(Console.ReadLine());
                if (oldOrderID < 0) { Console.WriteLine("请输入正确的订单号！"); return; }
                //else { ModifyOrder.OrderId = oldOrderID; }
                /*DeleteOrderByOrderID(oldOrderID);
                ModifyOrder.Client = ReadClientName();
                AddOrderItems(ModifyOrder);
                using(var context=new OrderContext())
                {
                    ModifyOrder.Client.Orders.Add(ModifyOrder);
                    context.Orders.Add(ModifyOrder);
                    context.SaveChanges();
                }*/
                using (var context = new OrderContext())
                {
                    List<OrderItem> orderItems = new List<OrderItem>();
                    var order = context.Orders.First(o => o.OrderId == oldOrderID);
                    context.OrderItems.Where(o => o.OrderId == order.OrderId)
                        .ForEachAsync(o => orderItems.Add(o));
                    orderItems.ForEach(o => context.OrderItems.Remove(o));
                    order.TotalMoney = 0;
                    order.Client = ReadClientName();
                    order.ClientName = order.Client.ClientName;
                    AddOrderItems(order);
                    context.SaveChanges();
                }
            }
            catch
            {
                Console.WriteLine("请输入正确的订单号！");
            }
        }

        //按订单号删除
        void DeleteOrderByOrderID(int oldOrderID)
        {
            using (var context = new OrderContext())
            {
                var order = context.Orders.Include("OrderItems")
                    .SingleOrDefault(o => o.OrderId == oldOrderID);
                if (order != null)
                {
                    context.Orders.Remove(order);
                    context.SaveChanges();
                }
                else { Console.WriteLine("没有该订单！"); }
            }

        }

        //按客户姓名查找
        void QueryByClientName(string clientName)
        {
            using (var context = new OrderContext())
            {
                context.Orders.Where(o => o.Client.ClientName == clientName).
                    ForEachAsync(o => Console.WriteLine(o));
            }
        }

        //按订单号查找
        void QueryByOrderID(int orderID)
        {
            using (var context = new OrderContext())
            {
                context.Orders.Where(o => o.OrderId == orderID)
                    .ForEachAsync(o => Console.WriteLine(o));
            }
        }

        //按商品名查找;
        void QueryByProductName(string productName)
        {
            using (var context = new OrderContext())
            {
                List<OrderItem> orderItems = new List<OrderItem>();
                context.OrderItems.Where(oi => oi.ProductName == productName)
                     .GroupBy(o => o.OrderId)
                     .ForEachAsync(o => orderItems.Add(o.First()));
                orderItems.ForEach(o =>
                Console.WriteLine(context.Orders.First(order => order.OrderId == o.OrderId)));
            }
        }

        //生成订单号
        int ProduceOrderID()
        {
            int orderID = -1;
            using (var context = new OrderContext())
            {
                context.Orders.Where(o => true).
                            ForEachAsync(o => { if (o.OrderId >= orderID) orderID = o.OrderId + 1; });
                return orderID;
            }
        }

        //录入客户信息
        Client ReadClientName()
        {
            string clientName = "";
            Client client = null; 
            using (var context = new OrderContext())
            {
                Console.WriteLine("输入客户姓名：");
                clientName = Console.ReadLine();
                //没有该客户则填入
                    var queryClient = context.Clients.Where(c => c.ClientName == clientName);
                    if (queryClient.Count()==0)
                    {
                        Client newClient = new Client(clientName);
                        newClient.Orders = new List<Order>();
                        context.Clients.Add(newClient);
                        client = newClient;
                    } else { client = queryClient.First(); }               
                return client;
            }
            
        }

        //展示所有商品
        void ShowOrders()
        {
            using (var context = new OrderContext())
            {
                Console.WriteLine("目前的商品有：");
                var queryProduct = context.Products.Where(b => true).GroupBy(p => p.ProductName)
                .ForEachAsync(q => Console.WriteLine(q.Key+": "+q.First().ProductPrice));
            }
        }

        //添加订单明细
        void AddOrderItems(Order newOrder)
        {
            bool quiet = false;
            int orderItemNumber = 0;
            int maxOrderItemNumber = 10;
            int productNumber = 0;
            string productName = "";
            Product newProduct=null ;
            while (!quiet && orderItemNumber <= maxOrderItemNumber)
            {
                Console.WriteLine("选择您要进行的操作： C：继续选择商品；Q：结束选择商品");
                switch (Console.ReadLine())
                {
                    case "C":
                        Console.WriteLine("选择您需要的商品：");
                        productName = Console.ReadLine();
                        using(var context=new OrderContext())
                        {
                            var queryProduct = context.Products.Where(p => p.ProductName == productName);
                            if (queryProduct.Count() == 0) { Console.WriteLine("此商品不存在！");break; }
                            else
                            {
                                newProduct = queryProduct.First();
                            }
                        }
                        Console.WriteLine("选择您需要的数目：");
                        try
                        {
                            productNumber = Convert.ToInt32(Console.ReadLine());
                            if (productNumber <= 0) { Console.WriteLine("请输入正确的数目！"); break; }
                            OrderItem orderItem = new OrderItem(10 * newOrder.OrderId + orderItemNumber,
                               newProduct,
                                productNumber, newOrder.OrderId);
                            orderItem.ProductName = newProduct.ProductName;
                            newOrder.AddOrderItem(orderItem);
                            orderItemNumber++;
                        }
                        catch { Console.WriteLine("请输入正确的数目！"); };
                        break;
                    case "Q":
                        quiet = true;
                        break;
                    default:
                        Console.WriteLine("请输入正确的操作！");
                        break;
                }
            }

        }
    }
}
